How C++ exceptions can be caught and re-thrown to be handled by higher-level functions?
How exceptions can be caught and re-thrown to be handled by higher-level functions?
393
16-Aug-2023
Updated on 17-Aug-2023
Aryan Kumar
17-Aug-2023Exceptions can be caught and re-thrown to be handled by higher level functions in C++ using the
throwkeyword. Thethrowkeyword is used to throw an exception. The exception can be any object, but it is usually astd::exceptionobject or a derived class ofstd::exception.To catch and re-throw an exception, you can use the
catchstatement. Thecatchstatement specifies the type of exception that you want to catch. If an exception of the specified type is thrown, thecatchstatement will be executed.The following code shows how to catch and re-throw an exception:
C++
In this code, the
foo()function throws astd::runtime_errorexception. Thebar()function catches this exception and then re-throws it. Themain()function catches the exception and prints a message to the console.It is important to note that the
re-thrownexception will be caught by the firstcatchstatement that matches its type. If there is nocatchstatement that matches the type of the exception, the program will terminate.Here are some additional things to keep in mind when catching and re-throwing exceptions:
catchstatement by using the|operator. For example, the following code catches bothstd::runtime_errorandstd::logic_errorexceptions:C++
You can also catch a wildcard exception by using the
catch (...)statement. Thecatch (...)statement will catch any exception, regardless of its type.It is important to handle all exceptions that are thrown by your code. If an exception is not handled, the program will terminate.